//
//  SoapRequestHelper.swift
//  WineComing
//
//  Created by xiaozhi on 15/7/29.
//  Copyright (c) 2015年 xiaozhi. All rights reserved.
//

import UIKit
let soapMessageStart = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>"
let soapMessageEnd = "</soap:Body></soap:Envelope>"
class SoapRequestHelper: NSObject {
    let session:NSURLSession = NSURLSession.sharedSession()
    var compeleteHandle:((NSData!, NSURLResponse!, NSError!) -> Void)?
    let baseUrl = "http://www.diyifw.com:8080/jll/services/JllService"
     func requestStart(method:String?,parameters:[(String,String)]?,compeleteHandle:((NSData!, NSURLResponse!, NSError!) -> Void)?){
        if let methodStr = method{
            var parameterString = NSMutableString()
            if let parameterArray = parameters{
                for (name,value) in parameterArray{
                    parameterString.appendString("<"+name+">"+value+"</"+name+">")
                }
                let bodyMessage = "<"+methodStr+"   xmlns=\"http://120.24.239.215/web/WebService.asmx\">"+(parameterString as String)+"</"+methodStr+">"
                let soapMessage:NSString = soapMessageStart + bodyMessage + soapMessageEnd
//                let request = NSMutableURLRequest(URL: NSURL(string: "http://www.diyifw.com:8080/jll/services/JllService")!)
                let request = NSMutableURLRequest(URL: NSURL(string: "http://120.24.239.215/web/WebService.asmx")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
                request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
                request.addValue("\(soapMessage.length)", forHTTPHeaderField: "Content-Length")
                request.addValue("http://tempuri.org/SendWirePoleCheckRecord", forHTTPHeaderField: "SOAPAction")
                request.HTTPMethod="POST"
                request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding)
                let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
                    let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    //                            println(string)
                    compeleteHandle!(string!.dataUsingEncoding(NSUTF8StringEncoding),response,error)
                })
                task.resume()
            }
            
        }
    }
    deinit{
        print("soapRequestHelper deinit")
    }
}
